package com.loren.demo03.tcp0;

import io.netty.buffer.ByteBuf;

import java.util.List;

public class MessageCodec {

    public void write(CustomProtocol msg, ByteBuf byteBuf) {
        byteBuf.writeByte(CustomProtocol.DATA_HEAD);
        byteBuf.writeInt(msg.getLength());
        byteBuf.writeBytes(msg.getContent());
        byteBuf.writeByte(CustomProtocol.DATA_TAIL);
    }

    public void decode(ByteBuf in, List<Object> out) {
        if (in.readableBytes() <= CustomProtocol.DATA_MIN_LENGTH) {
            return;
        }
        in.markReaderIndex();
        byte head = in.readByte();
        if (head != CustomProtocol.DATA_HEAD) {
            return;
        }
        int totalDataLength = in.readInt();
        int currentDataAndTailLength = in.readableBytes();
        if (totalDataLength >= currentDataAndTailLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] content = new byte[totalDataLength];
        in.readBytes(content);
        byte tail = in.readByte();
        if (tail == CustomProtocol.DATA_TAIL) {
            out.add(content);
        }
    }
}
